package bll

import (
	"fmt"

	"7qule.com/sd3/CrossServer/src/common/onlinelog"
	"7qule.com/sd3/CrossServer/src/common/systemConstant"

	"public.com/goutil/syncUtil"
)

type globalKuangzhanFighting struct {
	// 战斗节点信息
	data map[string]struct{}

	// 数据同步对象
	dataLock *syncUtil.RWLocker
}

var GlobalKuangzhanFightingBll = &globalKuangzhanFighting{
	dataLock: syncUtil.NewRWLocker(),
}

// --------------------------------外部方法--------------------------------------------------

//
// GetFightingInfo
// @Description: 获取镖局节点战斗信息
// @receiver this
// @param layerId:层数id
// @param positionId:节点id
// @return exist:是否正在战斗
//
func (this *globalKuangzhanFighting) GetFightingInfo(layerId, positionId int32) (exist bool) {
	if isOk, prevStack, currStack := this.dataLock.RLock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.RUnlock()

	nodeId := fmt.Sprintf("%v_%v", layerId, positionId)

	_, exist = this.data[nodeId]

	return
}

//
// AddFighting
// @Description:添加节点战斗信息
// @receiver this
// @param layerId:层数id
// @param positionId:节点id
//
func (this *globalKuangzhanFighting) AddFighting(layerId, positionId int32) (exist bool) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	nodeId := fmt.Sprintf("%v_%v", layerId, positionId)
	_, exist = this.data[nodeId]
	if exist {
		return
	}
	this.data[nodeId] = struct{}{}
	return false
}

//
// DeleteFighting
// @Description:删除节点战斗信息
// @receiver this
// @param layerId:层数id
// @param positionId:节点id
//
func (this *globalKuangzhanFighting) DeleteFighting(layerId, positionId int32) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	nodeId := fmt.Sprintf("%v_%v", layerId, positionId)

	delete(this.data, nodeId)
}
